/**
 * Created by Administrator on 2017/5/21.
 */
!function (win) {
    function resize() {
        var domWidth = domEle.getBoundingClientRect().width;
        if (domWidth / v > 750) {
            domWidth = 750 * v;
        }
        win.rem = domWidth / 16;
        domEle.style.fontSize = win.rem + "px";
    }

    var v, initial_scale, timeCode, dom = win.document, domEle = dom.documentElement,
        viewport = dom.querySelector('meta[name="viewport"]'), flexible = dom.querySelector('meta[name="flexible"]');
    if (viewport) {
        var o = viewport.getAttribute("content").match(/initial\-scale=(["']?)([\d\.]+)\1?/);
        if (o) {
            initial_scale = parseFloat(o[2]);
            v = parseInt(1 / initial_scale);
        }
    } else if (flexible) {
        var o = flexible.getAttribute("content").match(/initial\-dpr=(["']?)([\d\.]+)\1?/);
        if (o) {
            v = parseFloat(o[2]);
            initial_scale = parseFloat((1 / v).toFixed(2))
        }
    }
    if (!v && !initial_scale) {
        var n = (win.navigator.appVersion.match(/android/gi), win.navigator.appVersion.match(/iphone/gi));
        v = win.devicePixelRatio;
        v = n ? v >= 3 ? 3 : v >= 2 ? 2 : 1 : 1, initial_scale = 1 / v
    }
    //没有viewport标签的情况下
    if (domEle.setAttribute("data-dpr", v), !viewport) {
        if (viewport = dom.createElement("meta"), viewport.setAttribute("name", "viewport"), viewport.setAttribute("content", "initial-scale=" + initial_scale + ", maximum-scale=" + initial_scale + ", minimum-scale=" + initial_scale + ", user-scalable=no"), domEle.firstElementChild) {
            domEle.firstElementChild.appendChild(viewport)
        } else {
            var m = dom.createElement("div");
            m.appendChild(viewport), dom.write(m.innerHTML)
        }
    }
    win.dpr = v;
    win.addEventListener("resize", function () {
        clearTimeout(timeCode), timeCode = setTimeout(resize, 300)
    }, false);
    win.addEventListener("pageshow", function (b) {
        b.persisted && (clearTimeout(timeCode), timeCode = setTimeout(resize, 300))
    }, false);
    resize();
}(window);

/**
 * 加载样式
 * @type {{el: string, st: boolean, show: loader.show, close: loader.close}}
 */
var loader = {
    el: 'load_tag',
    st: false,
    ani: 2,
    ti: 5,
    show: function () {
        this.el = layer.open({'type': this.ani});
        this.st = true;
        this.clock();
    },
    close: function () {
        this.st && layer.close(this.el);
        this.st = false;
    },
    clock: function () {
        var clocker = setInterval(function () {
            if (loader.ti < 1) {
                loader.ti = 5;
                loader.close();
                clearInterval(clocker);
            } else {
                loader.ti--;
            }
        }, 1000);
    }
}

/**
 * 购物车
 * 本地存储的key要设置成带商家ID的，
 * 防止同一个用户打开了不同商家的店铺，会造成key值冲突
 */

var ShopCart = {
    storageKey: 'shopcart',
    data: {},
    init: function () {
        this.data = Local.get(this.storageKey) || {};
        if (this.count() > 9) {
            $('.cart-num').text('9+');
        } else {
            $('.cart-num').text(this.count());
        }
    },
    save: function () {
        Local.set(this.storageKey, this.data);
        if (this.count() > 9) {
            $('.cart-num').text('9+');
        } else {
            $('.cart-num').text(this.count());
        }
    },
    get: function (id) {
        this.init();
        return this.data[id] || 0;
    },
    add: function (id, num, messages) {
        this.init();
        messages = messages || [];
        num = parseInt(num);
        if (this.data[id]) {
            this.data[id].num += num;
            this.data[id].messages = messages;
        } else {
            this.data[id] = {
                num: num,
                messages: messages
            };
        }
        this.save();
    },
    mod: function (id, num) {
        this.init();
        num = parseInt(num);
        if (num > 0) {
            this.data[id].num = num;
            this.save();
        } else {
            this.del(id);
        }

    },
    del: function (id) {
        this.init();
        delete this.data[id];
        this.save();
    },
    clear: function () {
        this.data = {};
        this.save();
    },
    count: function () {
        if (!this.data) this.init();
        var count = 0;
        for (var x in this.data) {
            count += this.data[x];
        }
        if (count > 9) {
            return '9+';
        }
        return count;
    },
    setChecked: function (checked) {
        Local.set('shopcart.checked', checked);
    },
    clearChecked: function () {
        var checked = Local.get('shopcart.checked') || [];
        for (var x in checked) {
            this.del(checked[x]);
        }
        Local.remove('shopcart.checked');
    }
};

/**
 * 本地缓存对象
 */
var Local = {
    get: function (key) {
        var data = localStorage.getItem(key);
        try {
            return JSON.parse(data);
        } catch (e) {
            return data;
        }
    },
    set: function (key, data) {
        if ((typeof data) == 'object') {
            data = JSON.stringify(data);
        }
        localStorage.setItem(key, data);
    },
    remove: function (key) {
        localStorage.removeItem(key);
    },
    clear: function () {
        localStorage.clear();
    },
    flash: function (key, data) {
        if (!data) {
            data = this.get(key);
            this.remove(key);
            return data;
        } else {
            this.set(key, data);
        }
    }
};

function image(url, width, height, type) {
    width = width || 200;
    height = height || 200;
    type = type || 0;
    return url + '?imageView2/' + type + '/w/' + width + '/h/' + height;
}

/**
 * 12345 => $12,345.00
 *
 * @param {float}value {String} sign
 * @param  {String}_currency
 * @param {Number} decimals Decimal places
 */
function currency(value, _currency, decimals) {
    value = parseFloat(value);
    if (!isFinite(value) || !value && value !== 0) return '';
    _currency = _currency != null ? _currency : '￥';
    decimals = decimals != null ? decimals : 2;

    var stringified = Math.abs(value).toFixed(decimals);
    var _int = decimals ? stringified.slice(0, -1 - decimals) : stringified;
    var i = _int.length % 3;
    var head = i > 0 ? _int.slice(0, i) + (_int.length > 3 ? ',' : '') : '';
    var _float = decimals ? stringified.slice(-1 - decimals) : '';
    var sign = value < 0 ? '-' : '';
    return sign + _currency + head + _int.slice(i).replace(/(\d{3})(?=\d)/g, '$1,') + _float;
}


function malert(content, btn, callback) {
    if ($.isFunction(btn)) {
        callback = btn;
        btn = null;
    }
    mui.alert(content, " ", btn, callback);
}

function mconfirm(message, btns, yes, no) {
    if ($.isFunction(btns)) {
        no = yes;
        yes = btns;
        btns = null;
    }
    mui.confirm(message, ' ', btns, function (e) {
        if (e.index == 0) {
            no && no();
        } else {
            yes && yes();
        }
    });
}

function tips(message, callback) {
    layer.open({
        content: message,
        skin: 'msg',
        time: 2 //2秒后自动关闭
    });
    callback && setTimeout(callback, 2000);
}

function isString(data) {
    return typeof data == 'string' && data != '';
}

function isObject(data) {
    return typeof data == 'object' && (data != null);
}

function isFunction(data) {
    return typeof data == 'function';
}

function isUndefined(data) {
    return typeof data == 'undefined';
}

function isMobile(str) {
    return /^1[3|4|5|7|8]\d{9}$/.test(str);
}

function isWechat() {
    var ua = navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == "micromessenger") {
        return true;
    } else {
        return false;
    }
}

function isTime() {
    return parseInt((new Date()).getTime() / 1000);
}

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    },
    error: function (response, type) {
        layer.closeAll();
        if (type == 'error') {
            if (!response.responseJSON) {
                response.responseJSON = eval('(' + response.responseText + ')');
            }
            if (response.status == 401) {
                location.href = response.responseJSON.redirect;
            } else if (response.status == 422) {
                for (var x in response.responseJSON) {
                    return tips(response.responseJSON[x][0]);
                }
            } else {
                tips('服务器响应错误：[' + response.status + ']' + response.statusText);
            }
        } else if (type == 'timeout') {
            tips('请求超时');
        } else if (type == 'parsererror') {
            tips('服务器响应内容无法解析');
        } else if (type == 'notmodified') {
            tips('notmodified');
        }
    }
});

Date.prototype.format = function (format) {
    var $this = this;
    var date = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S+": this.getMilliseconds(),
        'w': function () {
            var weeks = new Array("日", "一", "二", "三", "四", "五", "六");
            var week = $this.getDay();
            return '星期' + weeks[week];
        }
    };
    if (/(y+)/i.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (var k in date) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ?
                date[k] : ("00" + date[k]).substr(("" + date[k]).length));
        }
    }
    return format;
}

function date(timestamp, format) {
    format = format || 'yyyy-MM-dd hh:mm:ss';
    var date = new Date();
    if (!timestamp) {
        return;
    } else {
        date.setTime(timestamp * 1000);
        return date.format(format);
    }

}

/**
 * 允许的mime类型
 * @type {[*]}
 */
var allowMimes = ['image/png', 'image/jpg', 'image/jpeg', 'image/gif'];
var allowSize = 4 * 1024 * 1024; //单位字节

function checkImageMime(file) {
    if (typeof file !== 'object') return false;
    return in_array(file.type, allowMimes);
}

function checkImageSize(file) {
    if (typeof file !== 'object') return false;
    return file.size <= allowSize;
}

/**
 * 数组中是否包含该元素
 * @param item
 * @param array
 * @returns {boolean}
 */
function in_array(item, array) {
    var result = false;
    for (var i in array) {
        if (array[i] == item) {
            result = true;
            break;
        }
    }
    return result;
}

/**
 * 根据传入的文件对象
 * 返回blob类型的可访问地址
 * @param files
 * @returns {Array}
 */
function getFileBlobUrl(file) {
    if (typeof file !== 'object') return '';
    return window.URL.createObjectURL(file);
}

function isWechat() {
    var ua = window.navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {
        return true;
    } else {
        return false;
    }
}

$(document).on("tap", "a", function () {

    var href = $(this).attr("href") || '';
    if (href != '' && href.indexOf("#") != 0 && href.indexOf("javascript:") != 0) {
        self.location = href;
        return false;
    }
});

function format_file_size(bytes) {
    if (!$.isNumeric(bytes)) return '';

    if (bytes < Math.pow(1024, 2)) return (bytes / Math.pow(1024, 1)).toFixed(2) + ' KB';

    if (bytes < Math.pow(1024, 3)) return (bytes / Math.pow(1024, 2)).toFixed(2) + ' MB';

    return (bytes / Math.pow(1024, 3)).toFixed(2) + ' GB';
}

window.Vue && Vue.filter('image', image);
window.Vue && Vue.filter('currency', currency);
window.Vue && Vue.filter('date', date);
window.Vue && Vue.filter('format_file_size', format_file_size);
ShopCart.init();

function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

/**
 * 倒计时
 * @param time 秒||日期格式
 * @param str
 * @returns {*}
 */
function countDown(time, str) {
    if (typeof end_time === "string") {
        var end_time = new Date(time).getTime()
    } else {
        end_time = time * 1000;
    }
    var left_seconds = (end_time - new Date().getTime()) / 1000;
    if (left_seconds > 0) {
        var day = Math.floor((left_seconds / 3600) / 24);
        var hour = Math.floor((left_seconds / 3600) % 24);
        var minute = Math.floor((left_seconds / 60) % 60);
        var second = Math.floor(left_seconds % 60);
        hour = (hour < 10 ? '0' : '') + hour.toString();
        minute = (minute < 10 ? '0' : '') + minute.toString();
        second = (second < 10 ? '0' : '') + second.toString();
        return !!str ? (day && day + '天') + (hour && hour + '时') + (minute && minute + '分') + (second && second + '秒') : [day, hour, minute, second];
    } else {
        return !!str ? '已过期' : [0, 0, 0, 0];
    }
}
